package Leetcode;

import base.TreeNode;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * 给定一个二叉树的根节点root，返回它的中序遍历 。
 */
public class 力扣94_二叉树的中序遍历 {

    public static void main(String[] args) {
        TreeNode a = new TreeNode(1);
        TreeNode b = new TreeNode(2);
        TreeNode c = new TreeNode(3);
        TreeNode d = new TreeNode(4);
        TreeNode e = new TreeNode(5);

        a.left = b;
        a.right = c;
        b.right = d;
        c.left = e;

        System.out.println(inorderTraversal(a));
    }

    static List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        inOrder1(result, root);
        return result;
    }

    // 使用递归
    static void inOrder1(List<Integer> list, TreeNode node) {
        if (node == null) {
            return;
        }
        inOrder1(list, node.left);
        list.add(node.val);
        inOrder1(list, node.right);
    }

    // 使用循环 栈
    static void inOrder2(List<Integer> result, TreeNode root) {
        Stack<TreeNode> stack = new Stack<>();
        while (root != null || !stack.isEmpty()) {
            while (root != null) {
                stack.push(root);
                root = root.left;
            }
            TreeNode pop = stack.pop();
            result.add(pop.val);
            root = pop.right;
        }
    }

}
